//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Icon,
  Button,
  message,
  Divider,
  Table,
  Modal,
  Select,
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import SelectDeptTree from '@/components/SelectDeptTree';
import ProDeptCreateForm from './ProOrganCreateForm'; //新增表单
import ProDeptUpdateForm from './ProOrganUpdateForm'; //修改表单
import ProDeptViewForm  from './ProOrganViewForm'; //查看表单

import styles from './ProOrganList.less';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

class StandardTable extends PureComponent {

  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
          scroll={{x: 'max-content'}}
          onRow={record => {
				    return {
				      onClick: event => {
				      	event.stopPropagation();
				      	router.push({
								  pathname: '/organ/organtree',
								  query: {
								    id: record.id,
								  },
								});
				      }, // 点击行
				    };
				  }}
        />
      </div>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ prodept, loading }) => ({
  prodept,
  loading: loading.models.prodept,
}))

@Form.create()
class ProDeptList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    viewModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    viewFormValues: {},

    currentPage: 1,
    pageSize: 10,
    addButtonVisible: 0,
    updateButtonVisible: 0,
    deleteButtonVisible: 0,
    requestModelName:"prodept",
  };

  columns = [

    {
      title: '名称',
      dataIndex: 'departmentname',
      key: 'departmentname',
    }, /* {
      title: '状态',
      dataIndex: 'childflag',
      key: 'childflag',
      render: (text,record) => {
      	return text == 'T'? (
      		<Button size="small" style={{fontSize: '12px',backgroundColor: "#e8f4ff",color: "#1890FF",border:'1px solid #d1e9ff'}}>可用</Button>
      	):(
      		<Button size="small" disabled style={{fontSize: '12px' }}>禁用</Button>
      	)
      }
    }, */ {
      title: '单位类型',
      dataIndex: 'dept_kind',
      key: 'dept_kind',
    }, {
      title: '创建时间',
      dataIndex: 'zb9991',
      key: 'zb9991',
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    }, {
      title: '操作',
			fixed:'right',
			align: 'center',
			width: 160,
      render: (text, record) => {
      	const { updateButtonVisible,deleteButtonVisible } = this.state;
      	return (
	        <Fragment>
							{/*<a onClick={() => this.handleViewModalVisible(true, record)}>查看</a>
							<Divider type="vertical" />
							{updateButtonVisible == 1?(
					    	<span><a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
					    	<Divider type="vertical" /></span>

					    ):null}
							{deleteButtonVisible == 1?
					    	record.key != "000000000000"? (
					    		<a onClick={() => this.handleDeleteRecord(record)}>删除</a>
								): (
									<a onClick={() => message.success('根节点不能删除')}>删除</a>
								)
					    :null}*/}
							{updateButtonVisible == 1?(
					    	<Button  type="primary"  icon="edit"  style={{marginRight: '5px'}} onClick={() => this.handleUpdateModalVisible(true, record)}></Button>
					    ):null}
					    {deleteButtonVisible == 1?
					    	record.key != "000000000000"? (
					    		<Button  type="danger" icon="delete"  onClick={() => this.handleDeleteRecord(record)}></Button>
								): (
									<Button  type="danger" icon="delete"  onClick={() => message.success('根节点不能删除')}></Button>
								):null}
			    </Fragment>
	      )
      }
    },
  ];


  componentDidMount() {
  	const { dispatch } = this.props;
    dispatch({
      type: 'prodept/query_page_for_prodept',
    });

  	if(localStorage.getItem('auth_button') == "undefined") return false;
  	const authButton = JSON.parse(localStorage.getItem('auth_button'));
  	// getNodeByNameAndCallbackProcess(authButton,"prodept",(item,index,arr) => {
	  //   	if(item.children) {
	  //   		item.children.map((item,index) => {
	  //   			if(item.button_type == "add") {
	  //   				this.setState({
	  //   					addButtonVisible: 1,
	  //   				})
	  //   			}else if(item.button_type == "update") {
	  //   				this.setState({
	  //   					updateButtonVisible: 1,
	  //   				})
	  //   			}else if(item.button_type == "delete") {
	  //   				this.setState({
	  //   					deleteButtonVisible: 1,
	  //   				})
	  //   			}
	  //   		})
	  //   	}
   //  })
  }



  handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;

			this.setState({
				currentPage: pagination.current,
				pageSize: pagination.pageSize,
				selectedRows: [],
			})

	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	      const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});

	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }

	    dispatch({
	      type: 'prodept/query_page_for_prodept',
	      payload: params,
	    });
  };

  previewItem = id => {
    router.push(`/profile/basic/${id}`);
  };

  handleFormReset = () => {
	    const { form, dispatch } = this.props;
	    form.resetFields();

	    this.setState({
		    	currentPage: 1,
					selectedRows: [],
		      formValues: {},
		  });

	    dispatch({
	      type: 'prodept/query_page_for_prodept',
	    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };


	    this.setState({
	    		currentPage: 1,
					selectedRows: [],
	        formValues: values,
	    });

      dispatch({
        type: 'prodept/query_page_for_prodept',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  handleViewModalVisible = (flag, record) => {
    this.setState({
      viewModalVisible: !!flag,
      viewFormValues: record || {},
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'prodept/insert_for_prodept',
      payload: {
        dept_name: fields.dept_name,
        parentid: fields.parentid,
        levelcode: fields.levelcode,
        parent_name: fields.parent_name,
        enable: fields.enable,
        dept_description: fields.dept_description,
        leaf: fields.leaf,
        icon: fields.icon,
        cls: fields.cls,
        dept_code: fields.dept_code,
      },
      callback:(res) => {
        	if(res.success) {
    					message.success('添加成功');
        	}else {
        			message.success('添加失败');
        	}
      }
    });

    this.setState({
			selectedRows: [],
		})

    this.handleModalVisible();

  };

	handleUpdate = fields => {

    const { dispatch } = this.props;
    const { currentPage,pageSize } = this.state;
    dispatch({
	      type: 'prodept/update_for_prodept',
	      payload: {
	        dept_id: fields.dept_id,
	        dept_name: fields.dept_name,
	        parentid: fields.parentid,
	        levelcode: fields.levelcode,
	        parent_name: fields.parent_name,
	        enable: fields.enable,
	        dept_description: fields.dept_description,
	        dept_code: fields.dept_code,
	        leaf: fields.leaf,
	        icon: fields.icon,
	        cls: fields.cls,
	        currentPage,
	        pageSize,
	      },
	      callback:(res) => {
	        	if(res.success) {
	    					message.success('修改成功');
	        	}else {
	        			message.success('修改失败');
	        	}
	      }
    });

    this.setState({
			selectedRows: [],
		})
    this.handleUpdateModalVisible();

  };

  handleDeleteRecord = record => {
	    const { dispatch } = this.props;
			const { currentPage,pageSize } = this.state;

	    confirm({
			    title: '您确定要删除此部门吗?',
			    okText: '确认',
			    cancelText: '取消',
			    onOk() {
			        dispatch({
				        type: 'prodept/delete_by_primarykey_for_prodept',
				        payload: {
			        		recordid: record.dept_id,
			        		currentPage,
	        				pageSize,
				        },
				        callback: (res) => {
				        	if(res.success) {
				    			message.success('删除成功');
				        	}else {
				        		message.success('删除失败');
				        	}
				        }
			        });
			    },
			    onCancel() {},
			});

	    this.setState({
				selectedRows: [],
			})
  };


  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
        <FormItem label="部门名称">
        {getFieldDecorator('dept_name')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="状态">
        {getFieldDecorator('enable')(
        		<Select placeholder="请选择" style={{ width: '100%' }}>
        		    <Option value="1">可用</Option>
                <Option value="0">禁用</Option>
            </Select>
        )}
				</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        展开 <Icon type="down" />
        </a>
        </span>
        </Col>
        </Row>
        </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
						<Col md={8} sm={24}>
				        <FormItem label="部门名称">
				        	{getFieldDecorator('dept_name')(<Input placeholder="请输入" />)}
								</FormItem>
				    </Col>
				    <Col md={8} sm={24}>
				        <FormItem label="状态">
				        {getFieldDecorator('enable')(
				        		<Select placeholder="请选择" style={{ width: '100%' }}>
				        		    <Option value="1">可用</Option>
				                <Option value="0">禁用</Option>
				            </Select>
				        )}
								</FormItem>
				    </Col>
	    			<Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
			        <Button type="primary" htmlType="submit">
			        	查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        	重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        	收起 <Icon type="up" />
			        </a>
			        </span>
						</Col>
    	</Row>
    {/*<div style={{ overflow: 'hidden' }}>
<div style={{ marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        收起 <Icon type="up" />
        </a>
        </div>
        </div>*/}
    </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      prodept: { data,selectDeptTree },
      loading,
    } = this.props;



    const { selectedRows, modalVisible, updateModalVisible, viewModalVisible, updateFormValues, viewFormValues,requestModelName,addButtonVisible } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      dispatch: this.props.dispatch,
			requestModelName,
      selectDeptTree,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      dispatch: this.props.dispatch,
			requestModelName,
      selectDeptTree,
    };
    const viewMethods = {
      handleViewModalVisible: this.handleViewModalVisible
    };
    return (
      <PageHeaderWrapper title="机构信息列表">
            <Card bordered={false}>
            <div className={styles.proDepttableList}>
            <div className={styles.proDepttableListForm}>{this.renderForm()}</div>
            <div className={styles.proDepttableListOperator}>
            {addButtonVisible == 1?(
            	<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
        				新增
        			</Button>
        		):null}
    		</div>
        <StandardTable
        rowKey={"id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>

        <ProDeptCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <ProDeptUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ProDeptViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
  }
}

export default ProDeptList;
